<?php

namespace App\Http\Controllers\Pc;

use App\Http\Controllers\Controller;
use App\Http\Requests\Base;
use App\Jobs\WarehouseStatJob;
use App\Models\BaseModel;
use App\Models\WarehouseStatMonthModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\InventoryModel;
use Illuminate\Support\Facades\Redis;

class InventoryController extends Controller
{
    private $model;
    private $request;

    public function __construct(Request $request)
    {
        $this->model = new InventoryModel();
        $this->request = $request;
    }
    //fba库存
    public function amazon_inventory(){
        $params = $this->request->all();

        $result = $this->model->getInventory($params);

        return $this->back('获取成功', '200', $result);
    }

    //fba库存合计
    public function amazon_inventory_total(){
        $params = $this->request->all();

        $result = $this->model->getInventoryTotal($params);

        return $this->back('获取成功', '200', $result);
    }

    //本地库存接口
    public function saihe_inventory(){
        $params = $this->request->all();

        $result = $this->model->getCloudInventory($params);

        return $this->back('获取成功', '200', $result);
    }

    //库存总表
    public function all_inventory(){
        $params = $this->request->all();

        $result = $this->model->getAllInventory($params);

        return $this->back('获取成功', '200', $result);
    }


    //同安仓库存-汇总-spu
    public function saihe_inventory_spu(){
        $params = $this->request->all();

        $params['house_id'] = 1;

        $result = $this->model->getSaiheInventoryBySpu($params);

        return $this->back($result['msg'], '200', $result['data']);
    
    }

    //生产组货入库
    public function ConfirmGroupOutInByOrderNo(){
        $params = $this->request->all();
        $result = $this->model->ConfirmGroupOutInByOrderNo($params);

        return $this->back('获取成功', '200', $result);
    
    }
    
    //同安仓库存-汇总-大类
    public function saihe_inventory_cate(){
        $params = $this->request->all();

        $params['house_id'] = 1;

        $result = $this->model->getSaiheInventoryByCate($params);

        return $this->back('获取成功', '200', $result);
    
    }

    //泉州仓库存-汇总-spu
    public function quanzhou_inventory_spu(){
        $params = $this->request->all();

        $params['house_id'] = 2;

        $result = $this->model->getSaiheInventoryBySpu($params);

        return $this->back('获取成功', '200', $result);

    }

    //泉州仓库存-汇总-大类
    public function quanzhou_inventory_cate(){
        $params = $this->request->all();

        $params['house_id'] = 2;

        $result = $this->model->getSaiheInventoryByCate($params);

        return $this->back('获取成功', '200', $result);
    
    }

    
    //海外仓库存-汇总-fasin
    public function inventory_fasin(){
        $params = $this->request->all();

        $result = $this->model->getInventoryByFasin($params);

        return $this->back('获取成功', '200', $result);
    
    }

    //海外仓库存-汇总-spu
    public function inventory_spu(){
        $params = $this->request->all();

        $result = $this->model->getInventoryBySpu($params);

        return $this->back('获取成功', '200', $result);
    
    }
    
    //海外仓库存-汇总-大类
    public function inventory_cate(){
        $params = $this->request->all();

        $result = $this->model->getInventoryByCate($params);

        return $this->back('获取成功', '200', $result);
    
    }


    //云仓库存-汇总-spu
    public function cloud_inventory_spu(){
        $params = $this->request->all();

        $result = $this->model->getCloudInventoryBySpu($params);

        return $this->back('获取成功', '200', $result);
    
    }
    
    //云仓库存-汇总-大类
    public function cloud_inventory_cate(){
        $params = $this->request->all();

        $result = $this->model->getCloudInventoryByCate($params);

        return $this->back('获取成功', '200', $result);
    
    }


    //根据装箱码获得详情
    public function GetCusByBoxCode(){
        $params = $this->request->all();

        $result = $this->model->GetCusByBoxCode($params);

        if($result['type']=='success'){
            return $this->back('请求成功!',200,$result);
        }else{
            return $this->back('请求失败!'.$result['msg'], 500);
        }
        // return $this->back('获取成功', '200', $result);
    
    }

    

    //泉州仓库存
    public function quanzhou_inventory(){
        $params = $this->request->all();

        $params['house_id'] = 2;
        $params['warehouse_id'] = 2;
        //新库存取值
        $result = $this->model->getCloudInventory($params);

//        $result = $this->model->getSaiheInventory($params);

        return $this->back('获取成功', '200', $result);
    }

    //同安仓出入库记录
    public function house_data(){
        $params = $this->request->all();

        $params['house_id'] = 1;

        $result = $this->model->houseData($params);

        return $this->back('获取成功', '200', $result);
    }

    //云仓库存
    public function cloud_inventory(){
        $params = $this->request->all();
        $params['warehouse_id'] = 3;

        $result = $this->model->getCloudInventory($params);

        return $this->back('获取成功', '200', $result);
    }

    //工厂虚拟仓库存
    public function factory_inventory(){
        $params = $this->request->all();

        $result = $this->model->factoryInventory($params);

        return $this->back('获取成功', '200', $result);
    }

    //工厂虚拟仓库存-sku合同明细
    public function factory_sku(){
        $params = $this->request->all();

        $result = $this->model->factorySku($params);

        return $this->back('获取成功', '200', $result);
    }

    //工厂寄存仓库存
    public function deposit_inventory(){
        $params = $this->request->all();

        $result = $this->model->getCloudInventory($params);

        return $this->back('获取成功', '200', $result);
    }

    //云仓出入库记录
    public function cloud_data(){
        $params = $this->request->all();

        $result = $this->model->cloudData($params);

        return $this->back('获取成功', '200', $result);
    }

    //泉州仓出入库记录
    public function quanzhou_data(){
        $params = $this->request->all();

        $params['house_id'] = 2;

        $result = $this->model->houseData($params);

        return $this->back('获取成功', '200', $result);
    }

    //商品调拨记录
    public function transfers_data(){

        $params = $this->request->all();

        $result = $this->model->transfers_data($params);

        return $this->back('请求成功', 200, $result);
    }

    public function GetBoxCodeList(){

        $params = $this->request->all();

        $result = $this->model->GetBoxCodeList($params);

        return $this->back('请求成功', 200, $result);
    }


    public function GetBoxCodeYsList(){

        $params = $this->request->all();

        $result = $this->model->GetBoxCodeYsList($params);

        return $this->back('请求成功', 200, $result);
    }

    
    
    //查看库位占用详情
    public function GetLocationInfo(){

        $params = $this->request->all();

        $result = $this->model->GetLocationInfo($params);

        return $this->back('请求成功', 200, $result);
    }

    //查看已占用库存明细
    public function get_push_info(){

        $params = $this->request->all();

        $result = $this->model->get_push_info($params);

        return $this->back('请求成功', 200, $result);
    }
    
    //商品调拨详情
    public function transfers_data_detail(){

        $params = $this->request->all();

        $result = $this->model->transfers_data_detail($params);

        if($result['code']==200){
            return $this->back('请求成功', $result['code'],$result['msg']);
        }else{
            return $this->back('请求失败', $result['code'],$result['msg']);
        }

    }

    //商品调拨详情列表-全
    public function goods_detail_list(){

        $params = $this->request->all();

        $result = $this->model->goods_detail_list($params);

        if($result['code']==200){
            return $this->back('请求成功', $result['code'],$result['data']);
        }else{
            return $this->back('请求失败', $result['code'],$result['msg']);
        }

    }

    

    public function transfers_data_detail_get(){
        $params = $this->request->all();

        $result = $this->model->transfers_data_detail_get($params);

        return $this->back($result['msg'], $result['code']);
    }

    //库存变动
    public function goods_transfers(){

        $params = $this->request->all();

        try {
            //code...
            $result = $this->model->goods_transfers($params);
        } catch (\Throwable $th) {
            //throw $th;
            $err['msg'] =  $th->getMessage();
            $err['line'] =  $th->getLine();
            $err['file'] =  $th->getFile();

            $this->AddSysLog($params,$err,'库存变动',__METHOD__);
            return $this->back(json_encode($err),500);
        }
      

        $this->AddSysLog($params,$result,'库存变动',__METHOD__);

        return $this->back($result['msg'],$result['code'],$result);
    }


    
    //获取出库类型详情
    public function GetOutTypeDetail(){
    
        $params = $this->request->all();

        $result = $this->model->GetOutTypeDetail($params);

        return $this->back($result,200);
    }
    

    //获取已推送订单（APP）
    public function GetOutPushOrder(){
        
        $params = $this->request->all();

        $result = $this->model->GetOutPushOrder($params);

        return $this->back($result,200);
    }

    //库存变动退货
    public function goods_transfers_back(){

        $params = $this->request->all();

        $result = $this->model->goods_transfers_back($params);

        return $this->back($result['msg'],$result['code']);
    }

    //推送云仓入库单或调拨出库单
    public function goods_cloud(){
        $params = $this->request->all();

        $result = $this->model->goods_cloud($params);

        if (!isset($result['code']) || $result['code'] !== 200){
            return $this->back('请求失败!'.$result['msg'] ?? '未知错误！', $result['code'] ?? 500);
        }else{
            return $this->back('请求成功!'.$result['msg'], $result['code'], $result['data'] ?? []);
        }
    }

    
    //压缩出库-预生成
    public function ContractOutYs(){
        $params = $this->request->all();

        $result = $this->model->ContractOutYs($params);

        if (!isset($result['code']) || $result['code'] !== 200){
            return $this->back('请求失败!'.$result['msg'] ?? '未知错误！', $result['code'] ?? 500);
        }else{
            return $this->back('请求成功!'.$result['msg'], $result['code'], $result['data'] ?? []);
        }
    }

    //压缩出库
    public function ContractOutYsNew(){
        $params = $this->request->all();

        $result = $this->model->ContractOutYsNew($params);

        if (!isset($result['code']) || $result['code'] !== 200){
            return $this->back('请求失败!'.$result['msg'] ?? '未知错误！', $result['code'] ?? 500);
        }else{
            return $this->back('请求成功!'.$result['msg'], $result['code'], $result['data'] ?? []);
        }
    }

    //压缩出库pdf
    public function save_ys_pdf(){
        $params = $this->request->all();

        $result = $this->model->save_ys_pdf($params);

        if (!isset($result['code']) || $result['code'] !== 200){
            return $this->back('请求失败!'.$result['msg'] ?? '未知错误！', $result['code'] ?? 500);
        }else{
            return $this->back('请求成功!'.$result['msg'], $result['code'], $result['data'] ?? []);
        }
    }
    
    
    //新接口

    //收货-入库
    public function V1ReceiveIn(){
        $params = $this->request->all();

        $result = $this->model->V1ReceiveIn($params);

        if (!isset($result['code']) || $result['code'] !== 200){
            return $this->back('请求失败!'.$result['msg'] ?? '未知错误！', $result['code'] ?? 500);
        }else{
            return $this->back('请求成功!'.$result['msg'], $result['code'], $result['data'] ?? []);
        }
    }

    //已确认
    public function V1Confim(){
        $params = $this->request->all();

        $result = $this->model->V1Confim($params);

        if($result['type']=='success'){
            return $this->back('请求成功!'.$result['msg'],200,$result['data']);
        }else{
            return $this->back('请求失败!'.$result['msg'], 500);
        }
    }


    public function V1ReceiveProduct(){
        $params = $this->request->all();

        $result = $this->model->V1ReceiveProduct($params);

        if($result['type']=='success'){
            return $this->back('请求成功!'.$result['msg'],200,$result['data']);
        }else{
            return $this->back('请求失败!'.$result['msg'], 500);
        }

    }

    public function V1PackIn(){
        $params = $this->request->all();

        $result = $this->model->V1PackIn($params);

        if($result['type']=='success'){
            return $this->back('请求成功!'.$result['msg'],200,$result);
        }else{
            return $this->back('请求失败!'.$result['msg'], 500);
        }

    }

    public function V1PackLog(){
        $params = $this->request->all();

        $result = $this->model->V1PackLog($params);

        if($result['type']=='success'){
            return $this->back('请求成功!'.$result['msg'],200,$result);
        }else{
            return $this->back('请求失败!'.$result['msg'], 500);
        }

    }

    public function V1SaveLog(){
        $params = $this->request->all();

        $result = $this->model->V1SaveLog($params);

        if($result['type']=='success'){
            return $this->back('请求成功!'.$result['msg'],200,$result);
        }else{
            return $this->back('请求失败!'.$result['msg'], 500);
        }

    }


    public function V1SaveProduct(){
        $params = $this->request->all();

        $result = $this->model->V1SaveProduct($params);

        if($result['type']=='success'){
            return $this->back('请求成功!'.$result['msg'],200,$result['data']);
        }else{
            return $this->back('请求失败!'.$result['msg'], 500);
        }

    }

    public function V1SaveIn(){
        $params = $this->request->all();

        $result = $this->model->V1SaveIn($params);

        if($result['type']=='success'){
            return $this->back('请求成功!'.$result['msg'],200,$result);
        }else{
            return $this->back('请求失败!'.$result['msg'], 500);
        }

    }


    

    public function V1GetProduct(){
        $params = $this->request->all();

        $result = $this->model->V1GetProduct($params);

        if($result['type']=='success'){
            return $this->back('请求成功!'.$result['msg'],200,$result['data']);
        }else{
            return $this->back('请求失败!'.$result['msg'], 500);
        }

    }




    //推送补货计划单
    public function goods_cloudOut(){
        $params = $this->request->all();

        $result = $this->model->goods_cloudOut($params);

        return $this->back( $result['msg'], $result['code']);
    }

    //确认入库数量
    public function confirmInhouse(){
        $params = $this->request->all();

        $result = $this->model->confirmInhouse($params);


        //加入日志
        $out_no = $params['order_no'];
        $log = db::table('inhouse_err_log')->where('out_no',$out_no)->first();
        $d['out_no'] = $out_no;
        $d['create_time'] = date('Y-m-d H:i:s',time());
        $d['msg'] = $result['msg'];
        if($log){
            db::table('inhouse_err_log')->where('id',$log->id)->update($d);
        }else{
            db::table('inhouse_err_log')->insert($d);
        }
        
       

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500);

    }

    /**
     * @Desc: //修改待推送库存变动数据
     * @author: 严威
     * @Time: 2023/4/7 16:37
     * @updateTime: 2023/4/7 16:37
     */
    public function update_goods_transfers(){
        $params = $this->request->all();

        $result = $this->model->update_goods_transfers($params);

        return $this->back($result['msg'], $result['code']);
    }

    /**
     * @Desc: //确认已接收数量
     * @author: 严威
     * @Time: 2023/4/8 15:41
     * @updateTime: 2023/4/8 15:41
     */
//    public function update_goods_receive(){
//        $params = $this->request->all();
//
//        $result = $this->model->update_goods_transfers($params);
//
//        return $this->back($result['msg'], $result['code']);
//    }

    //生成中转箱码
    public function create_transfer_box(){
        $params = $this->request->all();

        $result = $this->model->create_transfer_box($params);

        return $this->back($result['msg'], $result['code']);
    }

    //删除中转箱码
    public function delete_transfer_box(){
        $params = $this->request->all();

        $result = $this->model->delete_transfer_box($params);

        return $this->back($result['msg'], $result['code']);
    }

    //批次中转箱列表
    public function transfers_box_list(){
        $params = $this->request->all();

        $result = $this->model->transfers_box_list($params);

        return $this->back('获取成功', 200,$result);
    }

    //修改中转箱数量
    public function update_transfers_box(){
        $params = $this->request->all();

        $result = $this->model->update_transfers_box($params);

        return $this->back($result['msg'], $result['code']);
    }

    //显示中转箱数据明细
    public function transfers_box_detail(){
        $params = $this->request->all();

        $result = $this->model->transfers_box_detail($params);

        return $this->back('获取成功', 200,$result);
    }

    //库位上下架商品库存
    public function location_change(){
        $params = $this->request->all();

        try {
            //code...
            $result = $this->model->location_change($params);
        } catch (\Throwable $th) {
            //throw $th;
            $result['code'] = 500;
            $result['msg'] = $th->getFile().'-'.$th->getLine().'-'.$th->getMessage();
        }

        $name = '库位上下架商品库存';
        if ($params['type'] == 1) $name = '上架';
        if ($params['type'] == 2) $name = '下架';
        if ($params['type'] == 3) $name = '调整上架';
        if ($params['type'] == 5) $name = '验货上架';
        if ($params['type'] == 6) $name = '验货下架';

        $this->AddSysLog($params,$result,'商品上下架',__METHOD__);
        return $this->back($result['msg'], $result['code']);

    }


    //待分配入库列表
    public function GetTransfersDetailList()
    {
        $params = $this->request->all();

        $result = $this->model->GetTransfersDetailList($params);

        if($result['type']=='success'){
            return $this->back('获取成功', '200', $result);
        }else{
            return $this->back($result['msg'], '300');
        }
    }

    //分配入库
    public function SetTransfersPlan()
    {
        $params = $this->request->all();

        $result = $this->model->SetTransfersPlan($params);

        if($result['type']=='success'){
            return $this->back('获取成功', '200', $result);
        }else{
            return $this->back($result['msg'], '300');
        }
    }

    //获取比例
    public function GetProportion()
    {
        $params = $this->request->all();

        $result = $this->model->GetProportion($params);

        if($result['type']=='success'){
            return $this->back('获取成功', '200', $result);
        }else{
            return $this->back($result['msg'], '300');
        }
    }





    public function getCustomSkuLocationInventory()
    {
        $params = $this->request->all();

        $result = $this->model->getCustomSkuLocationInventory($params);

        return $this->back($result['msg'], 200,$result['data']);
    }

    //查询出库单可分配库位
    public function selectLocation(){
        $params = $this->request->all();

        $result = $this->model->selectLocation($params);

        return $this->back('获取成功', 200,$result);
    }

    //解锁出库单分配库位
    public function unlockInventory(){
        $params = $this->request->all();

        $result = $this->model->unlockInventory($params);

        return $this->back($result['msg'], $result['code']);
    }

    //修改出库单分配库位
    public function updateLocation(){
        $params = $this->request->all();

        $result = $this->model->updateLocation($params);

        return $this->back($result['msg'], $result['code']);
    }

    public function saveGoodsTransfersInfo()
    {
        $params = $this->request->all();
        $result = $this->model->saveGoodsTransfersInfo($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    //平台间调整库存
    public function adjustInventory()
    {
        $params = $this->request->all();

//        return $this->back('暂时维护中');

        if (empty($params['platform_id'])) {
            return $this->back('调出平台不能为空');
        }

        if (empty($params['receive_platform_id'])) {
            return $this->back('调入平台不能为空');
        }

        if ($params['platform_id'] == $params['receive_platform_id']) {
            return $this->back('调出平台和调入平台不能一样');
        }

        if (empty($params['warehouse_id'])) {
            return $this->back('仓库不能为空');
        }

        if (isset($params['sku_data']) && is_array($params['sku_data'])) {
            foreach ($params['sku_data'] as $k => $v) {
                if ($v['num'] <= 0) {
                    unset($params['sku_data'][$k]);
                }
            }
        }

        if (empty($params['sku_data'])) {
            return $this->back('sku数据不能为空');
        }

        $userId = $this->GetUserIdByToken($params['token']);

        $params['user_id'] = $userId;

        if ($params['platform_id'] != 4) {
            $userIds = db::table('xt_role_user_join as a')
                ->leftJoin('users as b', 'a.user_id', '=', 'b.id')
                ->where('a.role_id', 1)
                ->where('b.state', 1)
                ->orWhere('b.Id', 638)
                ->pluck('a.user_id');

            //开发组人员调库存
            if ($userIds->search($userId) !== false) {

                $result = $this->model->adjustInventory($params, 1);
                return $this->back($result['msg'], $result['code'], $result['data'] ?? []);
            }
        }




        $type  = $params['platform_id'] == 4 ? 1 : 2;
        $result = $this->model->adjustInventory($params, $type);

        return $this->back($result['msg'], $result['code'], $result['data'] ?? []);
    }

    //平台间调整库存详情
    public function adjustInventoryDetail()
    {
        $params = $this->request->all();
        if (empty($params['id'])) {
            return $this->back('详情id不能为空');
        }

        $info = DB::table('adjust_inventory_platform')->where('id', $params['id'])->first();

        if (!$info) {
            return $this->back('无此详情');
        }

        $warehouseArr = [1=> '同安仓', 2=>'泉州仓'];
        $info->warehouse_name = $warehouseArr[$info->warehouse_id] ?? '';


        $model = new BaseModel();
        $info->platform_name = $model->GetPlatform($info->platform_id)['name'];
        $info->receive_platform_name = $model->GetPlatform($info->receive_platform_id)['name'];
        $info->user_name = $model->GetUsers($info->user_id)['account'];

        $skuData = json_decode($info->ext, true);
        $skuId = array_column($skuData, 'custom_sku_id');
        $skuList = DB::table('self_custom_sku')->select('id', 'custom_sku', 'old_custom_sku')->whereIn('id', $skuId)->get()->keyBy('id');
        //查询库存
        $inventoryArr = (new BaseModel())->getInventoryDetailByWlp($skuId, [$info->warehouse_id], [], [$info->platform_id, $info->receive_platform_id]);

        foreach ($skuData as $key => $value) {
            $sku = $skuList[$value['custom_sku_id']] ?? null;
            $skuData[$key]['custom_sku'] = $sku ? ($sku->old_custom_sku ?: $sku->custom_sku) : '';

            $keyPre = $value['custom_sku_id'] . '_' . $info->warehouse_id . '_';//键前缀
            $platformInventory = $inventoryArr[$keyPre . $info->platform_id] ?? ['usable_num' => 0];//被调平台库存
            $receivePlatformInventory = $inventoryArr[$keyPre . $info->receive_platform_id] ?? ['usable_num' => 0];//调入平台库存

            $skuData[$key]['platform_inventory'] = $platformInventory['usable_num'];
            $skuData[$key]['receive_platform_inventory'] = $receivePlatformInventory['usable_num'];

        }
        $info->sku_data = $skuData;

        return $this->back('ok', '200', $info);
    }

    public function updateadjustInventoryDetail()
    {
        $params = $this->request->all();
        $result = $this->model->updateadjustInventoryDetail($params);
        $this->AddSysLog($params, $result, '平台调库申请数量修改', __METHOD__);
        
        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc:获取spu发货详情列表
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/12/7 10:51
     */
    public function getSpuShipmentDeatilList()
    {
        $params = $this->request->all();
        $result = $this->model->getSpuShipmentDeatilList($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    public function getSpuColorShipmentDeatilList()
    {
        $params = $this->request->all();
        $result = $this->model->getSpuColorShipmentDeatilList($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    public function getCustomSkuShipmentDeatilList()
    {
        $params = $this->request->all();
        $result = $this->model->getCustomSkuShipmentDeatilList($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    /**
     * @Desc:保存每月sku库存
     * @return null
     * @author: Liu Sinian
     * @Time: 2023/12/19 14:03
     */
    public function saveCustomSkuInventoryMonth()
    {
        $params = $this->request->all();
        $result = $this->model->saveCustomSkuInventoryMonth($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }

    public function confirmDeliveryTime()
    {
        $params = $this->request->all();
        $result = $this->model->confirmDeliveryTime($params);

        return $this->back($result['msg'] ?? '未知错误！', $result['code'] ?? 500, $result['data'] ?? []);
    }
}

